<template>
	<view class="container">
		<!-- Status Bar Height Placeholder -->
		<view :style="{ height: statusBarHeight + 'px' }"></view>
		<!-- Order Tabs -->
		<view class="tabs">
			<view class="tab-item" :class="{ 'active': activeTab === 0 }" @click="switchTab(0)">
				进行中
			</view>
			<!-- <view class="tab-item" :class="{ 'active': activeTab === 1 }" @click="switchTab(1)">
				退款中
			</view> -->
			<view class="tab-item" :class="{ 'active': activeTab === 1 }" @click="switchTab(1)">
				已完成
			</view>
			<view class="tab-item" :class="{ 'active': activeTab === 2 }" @click="switchTab(2)">
				已取消
			</view>
		</view>

		<!-- Active Orders -->
		<swiper class="swiper" :current="activeTab" @change="onSwiperChange" style="height:100%">
			<!-- Active Tab -->
			<!-- { height: swiperHeight + 'px' } -->
			<swiper-item>
				<scroll-view scroll-y="true" class="scroll-view" style="height:100%">
					<view class="no-order" v-if="activeOrders.length === 0">
						<image src="/static/no-order.png" mode="aspectFit" class="no-order-image"></image>
						<text class="no-order-text">暂无进行中的订单</text>
						<view class="go-rent-btn" @click="goToHome">去租用</view>
					</view>

					<view class="order-list" v-else>
						<view class="order-item" v-for="(order, index) in activeOrders" :key="index">
							<view class="order-header">
								<view class="order-number">订单号: {{ order.order_id }}</view>
								<view class="order-status">{{order.status == 'unpaid' ? "待支付":"使用中"}}</view>
							</view>
							<view class="station-info">
								<view class="station-icon">
									<text class="cuIcon-location"></text>
								</view>
								<view class="station-content">
									<view class="station-title">{{ order.station.title }}</view>
									<view class="station-address">{{ order.station.address }}</view>
								</view>
							</view>

							<view class="order-info" v-if="order.status !='unpaid'">
								<view class="info-item">
									<text class="info-label">开始时间:</text>
									<text class="info-value">{{ order.start_time }}</text>
								</view>
								<view class="info-item">
									<text class="info-label">租用时长:</text>
									<text class="info-value">{{ order.duration || '------' }}</text>
								</view>
							</view>
							<view class="order-info" v-else>
								<view class="info-item">
									<text class="info-label">付款倒计时:</text>
									<text class="info-value">{{ formatTime(order.duetime) }}</text>
								</view>
							</view>

							<view class="order-footer">
								<view class="order-price">
									<text>实付款: </text>
									<text class="price-symbol">￥</text>
									<text class="price-value">{{ order.fee }}</text>
								</view>
								<view class="order-actions">
									<view class="action-btn outline" @click="viewDetail(order)">
										查看详情
									</view>
									<!-- <view class="action-btn primary" @click="goPay(order)"
										v-if="order.status == 'unpaid'">
										去支付
									</view> -->
									<!-- <view class="action-btn primary" @click="finishOrder(order)"
										v-if="order.status == 'paid'">
										结束租用
									</view> -->
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</swiper-item>

			<!-- Refunding Tab -->
			<!-- <swiper-item>
				<scroll-view scroll-y="true" class="scroll-view" style="height:100%">
					<view class="no-order" v-if="refundingOrders.length === 0">
						<image src="/static/no-order.png" mode="aspectFit" class="no-order-image"></image>
						<text class="no-order-text">暂无退款中的订单</text>
						<view class="go-rent-btn" @click="goToHome">去租用</view>
					</view>

					<view class="order-list" v-else>
						<view class="order-item" v-for="(order, index) in refundingOrders" :key="index">
							<view class="order-header">
								<view class="order-number">订单号: {{ order.order_id }}</view>
								<view class="order-status refunding">退款中</view>
							</view>

							<view class="station-info">
								<view class="station-icon">
									<text class="cuIcon-location"></text>
								</view>
								<view class="station-content">
									<view class="station-title">{{ order.station.title }}</view>
									<view class="station-address">{{ order.station.address }}</view>
								</view>
							</view>

							<view class="order-info">
								<view class="info-item">
									<text class="info-label">开始时间:</text>
									<text class="info-value">{{ order.start_time }}</text>
								</view>
								<view class="info-item">
									<text class="info-label">结束时间:</text>
									<text class="info-value">{{ order.end_time }}</text>
								</view>
								<view class="info-item">
									<text class="info-label">退款金额:</text>
									<text class="info-value highlight">￥{{ order.fee - order.final_fee }}</text>
								</view>
							</view>

							<view class="order-footer">
								<view class="order-price">
									<text>退款状态: </text>
									<text class="refund-status">处理中</text>
								</view>
								<view class="order-actions">
									<view class="action-btn outline" @click="viewDetail(order)">
										查看详情
									</view>

								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</swiper-item> -->

			<!-- Completed Tab -->
			<swiper-item>
				<scroll-view scroll-y="true" class="scroll-view" :style="{ height: swiperHeight + 'px' }">
					<view class="no-order" v-if="completedOrders.length === 0">
						<image src="/static/no-order.png" mode="aspectFit" class="no-order-image"></image>
						<text class="no-order-text">暂无已完成的订单</text>
						<view class="go-rent-btn" @click="goToHome">去租用</view>
					</view>

					<view class="order-list" v-else>
						<view class="order-item" v-for="(order, index) in completedOrders" :key="index">
							<view class="order-header">
								<view class="order-number">订单号: {{ order.order_id }}</view>
								<view class="order-status completed">已完成</view>
							</view>

							<view class="station-info">
								<view class="station-icon">
									<text class="cuIcon-location"></text>
								</view>
								<view class="station-content">
									<view class="station-title">{{ order.station.title }}</view>
									<view class="station-address">{{ order.station.address }}</view>
								</view>
							</view>

							<view class="order-info">
								<view class="info-item">
									<text class="info-label">开始时间:</text>
									<text class="info-value">{{ order.start_time }}</text>
								</view>
								<view class="info-item">
									<text class="info-label">结束时间:</text>
									<text class="info-value">{{ order.end_time }}</text>
								</view>
								<view class="info-item">
									<text class="info-label">实际时长:</text>
									<text class="info-value">{{formatTime(order.duration)}}</text>
								</view>
							</view>

							<view class="order-footer">
								<view class="order-price">
									<text>实付款: </text>
									<text class="price-symbol">￥</text>
									<text class="price-value">{{ order.final_fee }}</text>
								</view>
								<view class="order-actions">
									<view class="action-btn outline" @click="viewDetail(order)">
										查看详情
									</view>
									<view class="action-btn primary" @click="rentAgain(order)">
										再次租用
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</swiper-item>
			
			<swiper-item>
				<scroll-view scroll-y="true" class="scroll-view" :style="{ height: swiperHeight + 'px' }">
					<view class="no-order" v-if="canceledOrder.length === 0">
						<image src="/static/no-order.png" mode="aspectFit" class="no-order-image"></image>
						<text class="no-order-text">暂无取消的订单</text>
					</view>
			
					<view class="order-list" v-else>
						<view class="order-item" v-for="(order, index) in canceledOrder" :key="index">
							<view class="order-header">
								<view class="order-number">订单号: {{ order.order_id }}</view>
								<view class="order-status canceled">已取消</view>
							</view>
			
							<view class="station-info">
								<view class="station-icon">
									<text class="cuIcon-location"></text>
								</view>
								<view class="station-content">
									<view class="station-title">{{ order.station.title }}</view>
									<view class="station-address">{{ order.station.address }}</view>
								</view>
							</view>
			
							<view class="order-info">
								<view class="info-item">
									<text class="info-label">开始时间:</text>
									<text class="info-value">{{ order.start_time }}</text>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</swiper-item>

		</swiper>


	</view>
</template>

<script>
	import {
		API_CONFIG
	} from "../../config/constants.js";
	export default {
		data() {
			return {
				statusBarHeight: 20, // 状态栏高度
				activeTab: 0, // 当前激活的选项卡索引
				swiperHeight: 500, // 滑块区域高度
				showQrCodeModal: false, // 是否显示二维码弹窗
				orderList:[],
			};
		},
		computed:{
			activeOrders(){
				return this.orderList.filter(item=>item.status=='unpaid' || item.status=='returned')
			},
			completedOrders(){
				return this.orderList.filter(item=>item.status=='completed')
			},
			refundingOrders(){
				return this.orderList.filter(item=>item.status=='refunding')
			},
			canceledOrder(){
				return this.orderList.filter(item=>item.status=='canceled')
			},
		},
		methods: {
			// 获取所有我的订单信息
			getMyOrderInfos() {
				const token = uni.getStorageSync("token");
				console.log("用户token", token);

				// 清空数组，确保数据更新
				this.activeOrders = [];
				this.completedOrders = [];
				this.refundingOrders = [];

				uni.request({
					url: API_CONFIG.baseUrl + "/babyCar.Order/getMyOrder",
					method: "GET",
					header: {
						"Authorization": token
					},
					success: (res) => {
						this.orderList = res.data.data;
					},
					fail: (err) => {
						console.error(err);
					}
				});
			},

			// 获取状态栏高度，用于自适应不同设备
			getStatusBarHeight() {
				const systemInfo = uni.getSystemInfoSync();
				this.statusBarHeight = systemInfo.statusBarHeight;
			},

			// 计算滑块区域高度，保证内容显示完整
			calculateSwiperHeight() {
				const systemInfo = uni.getSystemInfoSync();
				// 页面高度 = 屏幕高度 - 状态栏高度 - 导航栏高度 - 选项卡高度 - 底部导航高度
				this.swiperHeight = systemInfo.windowHeight - this.statusBarHeight - 44 - 50 - 50;
			},

			// 切换选项卡
			switchTab(index) {
				this.activeTab = index;
			},

			// 滑动swiper时触发，同步更新顶部选项卡
			onSwiperChange(e) {
				this.activeTab = e.detail.current;
			},

			// 查看订单详情
			viewDetail(order) {
				uni.navigateTo({
					url: "/mine-page/order/order_detail?id=" + order.order_id
				})
			},

			// 关闭二维码弹窗
			closeModal() {
				this.showQrCodeModal = false;
			},

			// 结束订单租用
			finishOrder(order) {
				uni.showModal({
					title: '确认结束租用',
					content: '确定要结束当前租用吗？请确保溜娃车已归还至站点',
					success: (res) => {
						if (res.confirm) {
							// 模拟结束租用过程，实际应调用API
							uni.showLoading({
								title: '处理中...'
							});

							setTimeout(() => {
								uni.hideLoading();

								// 从活跃订单中移除，添加到已完成订单
								const index = this.activeOrders.findIndex(o => o.orderNo === order
									.orderNo);
								if (index !== -1) {
									// 复制订单对象并修改状态
									const completedOrder = {
										...order,
										status: 2,
										statusText: '已完成',
										endTime: this.getCurrentTime(), // 设置当前时间为结束时间
										actualDuration: order.duration // 简化处理，实际应计算真实使用时长
									};

									// 从活跃订单移除
									this.activeOrders.splice(index, 1);
									// 添加到已完成订单列表头部
									this.completedOrders.unshift(completedOrder);

									uni.showToast({
										title: '租用已结束',
										icon: 'success'
									});
								}
							}, 1500);
						}
					}
				});
			},

			// 删除已完成的订单记录
			deleteOrder(order) {
				uni.showModal({
					title: '确认删除订单',
					content: '确定要删除此订单记录吗？',
					success: (res) => {
						if (res.confirm) {
							// 从已完成订单列表中删除
							const index = this.completedOrders.findIndex(o => o.orderNo === order.orderNo);
							if (index !== -1) {
								this.completedOrders.splice(index, 1);
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							}
						}
					}
				});
			},

			// 再次租用功能
			rentAgain() {
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: (res) => {
						let station_id = JSON.parse(res.result).station_id;
						let pile_idx = JSON.parse(res.result).pile_idx;
						uni.navigateTo({
							url: "/pages/rent/select?station_id=" + station_id + "&pile_idx=" +
								pile_idx
						})
					},
					fail: (err) => {
						console.error('扫码失败:', err);
						uni.showToast({
							title: '扫码已取消',
							icon: 'none'
						});
					}
				});
			},

			// 获取当前时间字符串，格式：YYYY-MM-DD HH:MM:SS
			getCurrentTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			// 将描述转为00:00:00 格式
			formatTime(seconds) {
				const hours = Math.floor(seconds / 3600).toString().padStart(2, '0');
				const minutes = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
				const remainingSeconds = (seconds % 60).toString().padStart(2, '0');
				return `${hours}:${minutes}:${remainingSeconds}`;
			},

			// 去支付
			// goPay(order) {
			// 	console.log(order);
			// },

			// 跳转到首页
			goToHome() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			},
			setDuetime(){
				const token = uni.getStorageSync("token");
				this.activeOrders.forEach((item)=>{
					if(item.status=="unpaid" && item.duetime>=0){
						item.duetime--
						if(item.duetime<=0){
							item.status='canceled'
							uni.request({
								url: API_CONFIG.baseUrl + "/babyCar.Order/updateStatus",
								method: "GET",
								header: {
									"Authorization": token
								},
								data:{
									order_id:item.order_id,
									status:'canceled'
								},
								success: (res) => {
									
								},
								fail: (err) => {
									console.error(err);
								}
							});
						}
					}
				})
			}
		},
		onLoad() {
			this.getMyOrderInfos();
			this.getStatusBarHeight();
			this.calculateSwiperHeight();
			setInterval(()=>{
				this.setDuetime()
			},1000)
		}
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #F8F8F8;
	}

	.nav-bar {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		height: 44px;
		background-color: #FFD000;
	}

	.nav-title {
		font-size: 18px;
		font-weight: bold;
		color: #333333;
	}

	.tabs {
		display: flex;
		flex-direction: row;
		height: 50px;
		background-color: #FFFFFF;
		border-bottom: 1px solid #EEEEEE;
	}

	.tab-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 50px;
		font-size: 16px;
		color: #666666;
		position: relative;
	}

	.tab-item.active {
		color: #333333;
		font-weight: bold;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 20px;
		height: 3px;
		background-color: #FFD000;
		border-radius: 3px;
	}

	.swiper {
		flex: 1;
	}

	.scroll-view {
		width: 100%;
	}

	.no-order {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 100px;
	}

	.no-order-image {
		width: 120px;
		height: 120px;
		margin-bottom: 20px;
	}

	.no-order-text {
		font-size: 16px;
		color: #999999;
		margin-bottom: 20px;
	}

	.go-rent-btn {
		width: 120px;
		height: 40px;
		background-color: #FFD000;
		color: #333333;
		font-size: 16px;
		border-radius: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.order-list {
		padding: 15px;
	}

	.order-item {
		background-color: #FFFFFF;
		border-radius: 10px;
		margin-bottom: 15px;
		overflow: hidden;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
	}

	.order-header {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		border-bottom: 1px solid #F5F5F5;
	}

	.order-number {
		font-size: 14px;
		color: #666666;
	}

	.order-status {
		font-size: 14px;
		color: #FF5000;
		font-weight: bold;
	}

	.order-status.completed {
		color: #00AA00;
	}

	.order-status.refunding {
		color: #FF9900;
	}
	.order-status.canceled {
		color: #c1c1c1;
	}
	.station-info {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 15px;
		border-bottom: 1px solid #F5F5F5;
	}

	.station-icon {
		width: 40px;
		height: 40px;
		background-color: #F5F5F5;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999999;
		font-size: 20px;
	}

	.station-content {
		flex: 1;
		margin-left: 10px;
	}

	.station-title {
		font-size: 16px;
		color: #333333;
		margin-bottom: 5px;
	}

	.station-address {
		font-size: 14px;
		color: #999999;
	}

	.order-info {
		padding: 15px;
		border-bottom: 1px solid #F5F5F5;
	}

	.info-item {
		display: flex;
		flex-direction: row;
		margin-bottom: 10px;
	}

	.info-item:last-child {
		margin-bottom: 0;
	}

	.info-label {
		width: 80px;
		font-size: 14px;
		color: #999999;
	}

	.info-value {
		flex: 1;
		font-size: 14px;
		color: #333333;
	}

	.info-value.highlight {
		color: #FF5000;
		font-weight: bold;
	}

	.order-footer {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
	}

	.order-price {
		font-size: 14px;
		color: #333333;
	}

	.price-symbol {
		font-size: 14px;
		color: #FF5000;
	}

	.price-value {
		font-size: 18px;
		color: #FF5000;
		font-weight: bold;
	}

	.order-actions {
		display: flex;
		flex-direction: row;
	}

	.action-btn {
		height: 36px;
		padding: 0 15px;
		margin-left: 10px;
		border-radius: 18px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
	}

	.action-btn.outline {
		border: 1px solid #DDDDDD;
		color: #666666;
	}

	.action-btn.primary {
		background-color: #FFD000;
		color: #333333;
	}

	.modal {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 999;
	}

	.modal-mask {
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.6);
	}

	.modal-content {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 80%;
		background-color: #FFFFFF;
		border-radius: 10px;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.modal-title {
		width: 100%;
		text-align: center;
		font-size: 18px;
		font-weight: bold;
		padding: 15px;
		border-bottom: 1px solid #F5F5F5;
	}

	.qrcode-container {
		padding: 20px;
	}

	.qrcode-image {
		width: 200px;
		height: 200px;
	}

	.qrcode-tips {
		font-size: 14px;
		color: #666666;
		margin-bottom: 20px;
	}

	.modal-close {
		width: 100%;
		height: 50px;
		line-height: 50px;
		text-align: center;
		font-size: 16px;
		color: #333333;
		border-top: 1px solid #F5F5F5;
	}

	.bottom-nav {
		display: flex;
		flex-direction: row;
		height: 50px;
		background-color: #FFFFFF;
		border-top: 1px solid #EEEEEE;
	}

	.nav-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.nav-icon {
		font-size: 24px;
		color: #999999;
	}

	.nav-text {
		font-size: 12px;
		color: #999999;
	}

	.nav-item.active .nav-icon,
	.nav-item.active .nav-text {
		color: #FFD000;
	}

	.refund-status {
		font-size: 14px;
		color: #FF9900;
		font-weight: bold;
	}
</style>